package com.jxwifi.cloud.quickcleanserver.mycenter;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.basicactivity.BasicActivity;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.idroid.utils.MToast;
import com.idroid.widget.LoadDialog;
import com.idroid.widget.Toaster;
import com.jxwifi.cloud.quickcleanserver.MainActivity;
import com.jxwifi.cloud.quickcleanserver.R;
import com.jxwifi.cloud.quickcleanserver.app.AccountMgr;
import com.jxwifi.cloud.quickcleanserver.app.CleanBasicActivity;
import com.jxwifi.cloud.quickcleanserver.app.CleaningApplication;
import com.jxwifi.cloud.quickcleanserver.app.StateUtils;
import com.jxwifi.cloud.quickcleanserver.app.UrlPool;
import com.jxwifi.cloud.quickcleanserver.bean.ChannelTraderBean;
import com.jxwifi.cloud.quickcleanserver.bean.InfoBean;
import com.jxwifi.cloud.quickcleanserver.bean.UploadBean;
import com.jxwifi.cloud.quickcleanserver.model.AuzImpl;
import com.jxwifi.cloud.quickcleanserver.okhttp.AuzHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.DataJson_Cb;
import com.jxwifi.cloud.quickcleanserver.okhttp.Params;
import com.jxwifi.cloud.quickcleanserver.presenter.AuthenticationPresenter;
import com.jxwifi.cloud.quickcleanserver.presenter.ContactPresenter;
import com.jxwifi.cloud.quickcleanserver.utils.AlterLocation;
import com.jxwifi.cloud.quickcleanserver.utils.Constants;
import com.jxwifi.cloud.quickcleanserver.utils.KAlertDialog;
import com.jxwifi.cloud.quickcleanserver.utils.LocationGaoDe;
import com.jxwifi.cloud.quickcleanserver.utils.PasswordLogin;
import com.jxwifi.cloud.quickcleanserver.utils.ToastUtils;
import com.jxwifi.cloud.quickcleanserver.view.ContactNameView;
import com.photo.PhotoPickerActivity;
import com.upload.BusinessModule;
import com.upload.ImgUpload;
import com.upload.UpLoadListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.REPattern;

/**
 * 认证信息
 * Created by Administrator on 2019/5/14.
 */

public class AuthenticationActivity extends CleanBasicActivity implements ContactNameView{

    private String TAG = this.getClass().getSimpleName();
    /**
     * 单选
     */
    public final static int MODE_SINGLE = 0;
    /**
     * 多选
     */
    public final static int MODE_MULTI = 1;
    private static final int PICK_PHOTO = 1;

    @Bind(R.id.et_my_authentication_name)
    EditText mEtMyAuthenticationName;//姓名
    @Bind(R.id.et_my_authentication_id)
    EditText mEtMyAuthenticationId;//身份证信息
    @Bind(R.id.et_my_authentication_channel)
    TextView txt_my_authentication_channel;
    @Bind(R.id.tv_my_authentication_city)
    EditText mTvMyAuthenticationCity;

    @Bind(R.id.img_my_authentication_id_positive)
    ImageView mImgMyAuthenticationIdPositive;
    @Bind(R.id.img_my_authentication_id_side)
    ImageView mImgMyAuthenticationIdSide;
    @Bind(R.id.tv_authentication_button)
    TextView mTvAuthenticationButton;
    @Bind(R.id.img_my_authentication)
    ImageView mImgMyAuthentication;

    private int authentication;//1正面 2反面
    private String mIsPositive="";//是否有上传正面 提交接口用到的数据
    private String mIsSide="";//是否有上传反面 提交接口用到的数据

    private AuthenticationPresenter authenticationPresenter;
    private List<ChannelTraderBean> mList;
    private ArrayList<String> mChannelNameList;//用于选择器显示
    private OptionsPickerView mHobbyPickerView;//选择器
    private LoadDialog mLoadDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_authentication);
        ButterKnife.bind(this);
        openEventBus();
        mLoadDialog = new LoadDialog(this,"");
        mLoadDialog.show();
        authenticationPresenter=new AuthenticationPresenter(this);
        initView();
        authenticationPresenter.initChannelProviderData();
    }

    public void initView(){
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);// 设置默认键盘不弹出
        new LocationGaoDe().init(getApplicationContext());
        LocationGaoDe.startLocation();

        if(StateUtils.YES.equals(AccountMgr.getIsAuth(mBaseContext))){
            mImgMyAuthentication.setBackgroundResource(R.mipmap.icon_authentication_wait);
        }else if(StateUtils.TRAIN_APPLY_ING.equals(AccountMgr.getIsAuth(mBaseContext))){
            Toast toast =Toast.makeText(mBaseContext, "培训审核中", Toast.LENGTH_SHORT);
            ToastUtils.showMyToast(toast,3000);
            mImgMyAuthentication.setBackgroundResource(R.mipmap.icon_authentication_commit);
        }else if(StateUtils.COMPANY_APPLY_ING.equals(AccountMgr.getIsAuth(mBaseContext))){
            Toast toast =Toast.makeText(mBaseContext, "公司审核中", Toast.LENGTH_SHORT);
            ToastUtils.showMyToast(toast,3000);
            mImgMyAuthentication.setBackgroundResource(R.mipmap.icon_authentication_commit);
        }else if (StateUtils.NO.equals(AccountMgr.getIsAuth(mBaseContext))){ //审核失败后提示信息
            Toast toast =Toast.makeText(mBaseContext, "认证审核不通过，请重新提交审核", Toast.LENGTH_SHORT);
            ToastUtils.showMyToast(toast,3000);
            mImgMyAuthentication.setBackgroundResource(R.mipmap.icon_authentication_no);
        }else if (StateUtils.WAIT.equals(AccountMgr.getIsAuth(mBaseContext))){ //未提交审核信息
            mImgMyAuthentication.setBackgroundResource(R.mipmap.icon_authentication_no);
        }

        if (!TextUtils.isEmpty(AccountMgr.getrealName(mBaseContext))){
            mEtMyAuthenticationName.setText(AccountMgr.getrealName(mBaseContext));
        }

        if (!TextUtils.isEmpty(AccountMgr.getIdCardNum(mBaseContext))){
            mEtMyAuthenticationId.setText(AccountMgr.getIdCardNum(mBaseContext));
        }

        if (!TextUtils.isEmpty(AccountMgr.getNowAddress(mBaseContext))){
            mTvMyAuthenticationCity.setText(AccountMgr.getNowAddress(mBaseContext));
        }
        if (!TextUtils.isEmpty(AccountMgr.getIdCardImgBack(mBaseContext))){
            Glide.with(mBaseContext).load(AccountMgr.getIdCardImgBack(mBaseContext)).into(mImgMyAuthenticationIdSide);//mImgMyAuthenticationIdPositive
            mIsSide=AccountMgr.getIdCardImgBack(mBaseContext);
        }
        if (!TextUtils.isEmpty(AccountMgr.getIdCardImgFront(mBaseContext))){
            Glide.with(mBaseContext).load(AccountMgr.getIdCardImgFront(mBaseContext)).into(mImgMyAuthenticationIdPositive);
            mIsPositive=AccountMgr.getIdCardImgFront(mBaseContext);
        }
        //判断是否认证成功，成功后与认证中不可点击操作，其他状态下可以操作
        if (StateUtils.YES.equals(AccountMgr.getIsAuth(mBaseContext))||StateUtils.TRAIN_APPLY_ING.equals(AccountMgr.getIsAuth(mBaseContext))
                ||StateUtils.COMPANY_APPLY_ING.equals(AccountMgr.getIsAuth(mBaseContext))){
            mImgMyAuthenticationIdPositive.setClickable(false);
            mImgMyAuthenticationIdSide.setClickable(false);
            mEtMyAuthenticationId.setEnabled(false);
            txt_my_authentication_channel.setEnabled(false);
            mEtMyAuthenticationName.setEnabled(false);
            mTvMyAuthenticationCity.setEnabled(false);
            mTvAuthenticationButton.setVisibility(View.GONE);
        }else{
            mTvAuthenticationButton.setVisibility(View.VISIBLE);
            mImgMyAuthenticationIdPositive.setClickable(true);
            mImgMyAuthenticationIdSide.setClickable(true);
            mEtMyAuthenticationName.setEnabled(true);
            mEtMyAuthenticationId.setEnabled(true);
            txt_my_authentication_channel.setEnabled(true);
            mTvMyAuthenticationCity.setEnabled(true);
        }

    }



    @OnClick({R.id.rel_img_back_pressed,R.id.img_my_authentication_id_positive,R.id.img_my_authentication_id_side,
    R.id.tv_authentication_button,R.id.et_my_authentication_channel})
    void clickCK(View v){
        Intent intent = new Intent();
        switch (v.getId()){
            //返回按钮
            case R.id.rel_img_back_pressed:
                onBackPressed();
                break;
            //身份证正面
            case R.id.img_my_authentication_id_positive:
                initphone(1);
                break;
            //身份证反面
            case R.id.img_my_authentication_id_side:
                initphone(2);
                break;
            //渠道商选择
            case R.id.et_my_authentication_channel:
                if (LocationGaoDe.getLatitude()==0.0){
                    AlterLocation.popAlterDialog(mBaseContext, "定位服务已关闭", "请检查手机中定位是否开启");
                }else {
                    mHobbyPickerView.show();
                }
                break;
            //保存按钮
            case R.id.tv_authentication_button:
                if (TextUtils.isEmpty(mEtMyAuthenticationName.getText().toString())){
                    Toast toast =Toast.makeText(mBaseContext, "姓名不能未空，请输入", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                    return;
                }
                if (!REPattern.isConfirmCode(mEtMyAuthenticationId.getText().toString())){
                    Toast toast =Toast.makeText(mBaseContext, "身份证号不正确，请重新输入", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                    return;
                }
                if (TextUtils.isEmpty(mIsPositive)||TextUtils.isEmpty(mIsSide)){
                    Toast toast =Toast.makeText(mBaseContext, "请上传身份证照片", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                    return;
                }
                if (TextUtils.isEmpty(mTvMyAuthenticationCity.getText().toString())){
                    Toast toast =Toast.makeText(mBaseContext, "请输入您的地址", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                    return;
                }
                if(TextUtils.isEmpty(txt_my_authentication_channel.getText().toString())){
                    Toast toast =Toast.makeText(mBaseContext, "请选择渠道商", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                    return;
                }
                initdata();
                break;
        }
    }

    public void initdata(){
        Params params=new Params();
        params.add("idCardImgBack",mIsSide);
        params.add("idCardImgFront",mIsPositive);
        params.add("idCardNum",mEtMyAuthenticationId.getText().toString());
        params.add("nowAddress",mTvMyAuthenticationCity.getText().toString());
        params.add("realName",mEtMyAuthenticationName.getText().toString());
        params.add("serviceCode",getServiceCode(txt_my_authentication_channel.getText().toString()));
        AuzHttp.post(UrlPool.POST_UPDATE_AUTH,params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code==0){
                    InfoBean mInfoBean= JSON.parseObject(data, InfoBean.class);
                    AccountMgr.putUser(mBaseContext,mInfoBean,false);
                    Toast toast =Toast.makeText(mBaseContext, "认证已提交", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);

                    Intent intent=new Intent();
                    CleaningApplication.JUMP_TYPE=0;
                    intent.setClass(mBaseContext, MainActivity.class);
                    intent.putExtra("mainindex", "0");
                    startActivity(intent);
                    finish();
                }else{
                    PasswordLogin.passwordlogin(mBaseContext,TAG,AccountMgr.gettell(mBaseContext),AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin){
                        initdata();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);
            }
        },TAG);

    }
    public void initphone(int cation){
        if (isPermissionGranted(Manifest.permission.CAMERA,
                Constants.QUEST_CODE_CAMERA)) {
            Intent intent=new Intent();
            intent.setClass(mBaseContext, PhotoPickerActivity.class);
            intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);//是否显示相机
            intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, MODE_SINGLE);//单选还是多选
            intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, 1);//最多可选择数量
            startActivityForResult(intent, PICK_PHOTO);
            authentication=cation;
        } else {
            if (Build.VERSION.SDK_INT <= 22) {
                final KAlertDialog dialog = new KAlertDialog(mBaseContext, "相机权限已关闭\", \"相机权限已被禁止，请在设置中开启");
                dialog.setRightTxt("去查看", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //前往应用详情界面
                        try {
                            Uri packUri = Uri.parse("package:" + mBaseContext.getPackageName());
                            Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packUri);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        } catch (Exception e) {
                            MToast.shortToast(mBaseContext, "跳转失败");
                        }
                        dialog.dismiss();
                    }
                });
                dialog.setLeftTxt("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        }
    }

    /**
     * 图片选择回调的方法
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_PHOTO) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                Log.w("oushuhua","result"+result.get(0));
                uploadImg(result.get(0));
            }
        }
    }

    //图片上传
    public void uploadImg(String img){
        new ImgUpload(mBaseContext, UrlPool.STORAGE_UPLOAD, img, new UpLoadListener() {
            @Override
            public void onComplete(boolean isSuccess, String response) {

                if (isSuccess) {
                    UploadBean muploadbean = JSON.parseObject(response, UploadBean.class);
                    if (authentication==1){
                        Glide.with(mBaseContext).load(muploadbean.getUrl()).into(mImgMyAuthenticationIdPositive);
                        mIsPositive=muploadbean.getUrl();
                    }else if (authentication==2){
                        Glide.with(mBaseContext).load(muploadbean.getUrl()).into(mImgMyAuthenticationIdSide);
                        mIsSide=muploadbean.getUrl();
                    }

                } else {
                    Toaster.show(getApplicationContext(), "上传失败，请重试");
                }

            }
        }, TAG).setBusinessModule(BusinessModule.Head).doUpload();
    }

    protected boolean isPermissionGranted(String permissionName, int questCode) {
        //6.0以下系统，取消请求权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        //判断是否需要请求允许权限，否则请求用户授权
        int hasPermision = mBaseContext.checkSelfPermission(permissionName);
        if (hasPermision != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{permissionName}, questCode);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length == 0) {
            return;
        }
        switch (requestCode) {
            case Constants.QUEST_CODE_CAMERA:
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions,
                        grantResults);
                break;
        }
    }

    public void initChannelProviderSelector(){

        mHobbyPickerView= new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                txt_my_authentication_channel.setText(mChannelNameList.get(options1));

            }
        }).setDecorView((RelativeLayout)findViewById(R.id.activity_rootview))//必须是RelativeLayout，不设置setDecorView的话，底部虚拟导航栏会显示在弹出的选择器区域
                .setTitleText("选择渠道商")//标题文字
                .setTitleSize(20)//标题文字大小
                .setTitleColor(getResources().getColor(R.color.pickerview_title_text_color))//标题文字颜色
                .setCancelText("取消")//取消按钮文字
                .setCancelColor(getResources().getColor(R.color.pickerview_cancel_text_color))//取消按钮文字颜色
                .setSubmitText("确定")//确认按钮文字
                .setSubmitColor(getResources().getColor(R.color.pickerview_submit_text_color))//确定按钮文字颜色
                .setContentTextSize(20)//滚轮文字大小
                .setTextColorCenter(getResources().getColor(R.color.pickerview_center_text_color))//设置选中文本的颜色值
                .setLineSpacingMultiplier(1.8f)//行间距
                .setDividerColor(getResources().getColor(R.color.pickerview_divider_color))//设置分割线的颜色
                .setSelectOptions(0)//设置选择的值
                .build();
        mHobbyPickerView.setPicker(mChannelNameList);

    }


    @Override
    public String getContactName() {
        return null;
    }

    @Override
    public void onSuccess(int code, String data) {
        if (code == 0) {
            mLoadDialog.dismiss();
            mList = JSON.parseArray(data, ChannelTraderBean.class);
            if (!TextUtils.isEmpty(AccountMgr.getServiceCode(mBaseContext))){
                txt_my_authentication_channel.setText(getRealName(AccountMgr.getServiceCode(mBaseContext)));
            }
            mChannelNameList = new ArrayList<String>();
            for(ChannelTraderBean channelTraderBean : mList){
                mChannelNameList.add(channelTraderBean.getRealName());
            }
            initChannelProviderSelector();
        }
    }

    @Override
    public void onFailure(int errorCode, String msg) {
        mLoadDialog.dismiss();
        Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast,3000);
    }

    /**
     * 根据所选渠道商名字获取ServiceCode
     * @param realName
     */
    public String getServiceCode(String realName){
        String serviceCode = "";
        for (int i = 0; i < mList.size(); i++) {
                if (mList.get(i).getRealName().equals(realName)){
                    serviceCode = mList.get(i).getServiceCode();
                    break;
                }
        }
        Log.i(TAG,"getServiceCode ==> realName = "+realName+" serviceCode = "+serviceCode);
        return serviceCode;
    }

    /**
     * 根据渠道商编码获取到渠道商名称
     * @param serviceCode
     * @return
     */
    public String getRealName(String serviceCode){
        String realName = "";
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).getServiceCode().equals(serviceCode)){
                realName = mList.get(i).getRealName();
                break;
            }
        }
        Log.i(TAG,"getServiceCode ==> realName = "+realName+" serviceCode = "+serviceCode);
        return realName;
    }


}
